package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import tools.Utility;

import beans.*;

public class AdminDispatcher extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	private static String pageAdmin = null;
	private static String pageOrder = null;
	private static String pageProduct = null;
	private static String pageNewProduct = null;
	private static String pageComponent = null;
	private static String pageError = null;

	private static final  String ASSEMBLE_LIST = "assemble_list";
	
	

	private static String pageOrderDetail = null;

	private static final String ERROR = "errorMessage";


	public AdminDispatcher() {
		super();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);

		// get pages path

		pageAdmin = config.getInitParameter("PAGE_ADMIN");
		pageOrder = config.getInitParameter("PAGE_ORDER");
		pageProduct = config.getInitParameter("PAGE_PRODUCT");
		pageComponent = config.getInitParameter("PAGE_COMPONENT");
		pageOrderDetail = config.getInitParameter("PAGE_ORDERDETAIL");
		pageError = config.getInitParameter("PAGE_ERROR");
		pageNewProduct = config.getInitParameter("PAGE_NEW_PRODUCT");

	}

	/**
	 * The processRequest method of the servlet. <br>
	 * 
	 * This method is called when a request is received
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	@SuppressWarnings("unchecked")
	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");

		if (action == null) {
			action = "admin";
		}

		if (action.equals("admin")) {
			request.getRequestDispatcher(pageAdmin).forward(request, response);
		} else if (action.equals("order")) {
			OrderList orders = new OrderList();

			orders.setUndeliveryedOrder();
			request.setAttribute("ORDERS", orders);

			request.getRequestDispatcher(pageOrder).forward(request, response);
		} else if (action.equals("orderdetail")) {
			String orderid = request.getParameter("orderid");
			try {
				OrderBean order = new OrderBean();
				order.setOrderbyID(Integer.parseInt(orderid));
				request.setAttribute("ORDERDETAIL", order);

				CartBean cart = Utility
						.ConvertProductString_to_ProductList(order
								.getProductString());
				request.setAttribute("ORDERPRODUCTS", cart);

				request.getRequestDispatcher(pageOrderDetail).forward(request,
						response);

			} catch (Exception e) {

			}
		} else if (action.equals("delivery")) {
			OrderBean order = new OrderBean();
			String orderid = request.getParameter("orderid");
			try {
				int orderID = Integer.parseInt(orderid);
				if (order.deliver(orderID)) {
					OrderList orders = new OrderList();

					orders.setUndeliveryedOrder();
					request.setAttribute("ORDERS", orders);
					request.getRequestDispatcher(pageOrder).forward(request,
							response);
				} else {
					gotoErrorPage(request, response,
							"Some error occur in the operation of delivery!");
				}
			} catch (Exception e) {
				gotoErrorPage(request, response,
						"Some error occur in the operation of delivery!");
			}
		} else if (action.equals("product")) {
			request.getRequestDispatcher(pageProduct)
					.forward(request, response);
		} else if (action.equals("component")) {
			request.getRequestDispatcher(pageComponent).forward(request,
					response);
		} else if (action.equals("com_update")) {
			Map<String, String[]> componentmap = (Map<String, String[]>) request
					.getParameterMap();
			Set<Map.Entry<String, String[]>> components = componentmap
					.entrySet();
			Iterator<Map.Entry<String, String[]>> iterator = components
					.iterator();

			while (iterator.hasNext()) {
				Map.Entry<String, String[]> entry = iterator.next();
				String parameterName = entry.getKey();
				String parameterValue = entry.getValue()[0];

				if (parameterName.indexOf("quantity_", 0) != -1) {
					try {
						int componentID = Integer.parseInt(parameterName
								.split("_")[1]);
						int componentNumber = Integer.parseInt(parameterValue);
						ComponentBean cb = new ComponentBean();
						cb.setId(componentID);
						cb.setQuantity(componentNumber);
						cb.updateComponentByID();
					} catch (Exception e) {
					}
				}
			}
			String newname = request.getParameter("new_name");
			if (newname != null && !newname.equals("")) {
				ComponentBean cb = new ComponentBean();
				cb.setName(newname.trim());
				cb.setQuantity(Integer.parseInt(request.getParameter(
						"new_quantity").trim()));
				cb.setComments(request.getParameter("new_comments"));

				cb.insertComponent();
			}
			request.getRequestDispatcher(pageComponent).forward(request,
					response);
		}

		else if (action.equals("pro_update")) {
			Map<String, String[]> productmap = (Map<String, String[]>) request
					.getParameterMap();
			Set<Map.Entry<String, String[]>> products = productmap.entrySet();
			Iterator<Map.Entry<String, String[]>> iterator = products
					.iterator();

			while (iterator.hasNext()) {
				Map.Entry<String, String[]> entry = iterator.next();
				String parameterName = entry.getKey();
				String parameterValue = entry.getValue()[0];

				if (parameterName.indexOf("price_", 0) != -1) {
					try {
						int productID = Integer.parseInt(parameterName
								.split("_")[1]);
						double productPrice = Double
								.parseDouble(parameterValue);
						ProductBean cb = new ProductBean();
						cb.setId(productID);
						cb.setPrice(productPrice);
						cb.updateProductByID();
					} catch (Exception e) {
					}
				}

			}

			request.getRequestDispatcher(pageProduct)
					.forward(request, response);
		}
		else if(action.equals("addproduct"))
		{
			request.getRequestDispatcher(pageNewProduct).forward(request,response);
		}
		else if(action.equals("new_product"))
		{
			HttpSession sess=request.getSession();
			
			AssembleList assembles = (AssembleList)sess.getAttribute(ASSEMBLE_LIST);
			if (assembles!=null)
			{
				String proname=request.getParameter("pro_name");
				
			    String procate=request.getParameter("pro_category");
			    int cate=Utility.ConvertCategory(procate);
			    
			    String proprice=request.getParameter("pro_price");
			    String proimage=request.getParameter("pro_image");
			    String prodesc=request.getParameter("pro_desc");
			    
			    ProductBean pb=new ProductBean();
			    pb.setName(proname);
			    pb.setCategory(cate);
			    pb.setPrice(Double.parseDouble(proprice));
			    
			    pb.setImage(Utility.convertCategoryInt_to_imagePath(cate) + proimage);
			    pb.setDesc(prodesc);
			    
			    pb.insertProduct();
			    
			    pb.maxProductID();
			    int proid=pb.getID();
			    
			    Iterator<AssembleBean> it=assembles.getComponents().iterator();
			    
			    while(it.hasNext())
			    {
			    	AssembleBean ab=it.next();
			    	ab.insertAssemble(proid);
			    }
			    
			    sess.removeAttribute(ASSEMBLE_LIST);
			}
			
			request.getRequestDispatcher(pageNewProduct).forward(request,response);
		}	
		else if(action.equals("assemble_component"))
		{
			HttpSession sess=request.getSession();
			AssembleList assembleList = (AssembleList)sess.getAttribute(ASSEMBLE_LIST);
			
			String compo=request.getParameter("add_component");
		    String assnum=request.getParameter("pro_assnum");
		  
		    AssembleBean ab=new AssembleBean();
		    ab.setComponentID(Integer.parseInt(compo));
		    ab.setComponentNO(Integer.parseInt(assnum));
		    
		    
			if(assembleList == null){
				assembleList= new AssembleList();
			}
			
			boolean addFlag = true;
			for(int i = 0; i < assembleList.getComponents().size(); i++){
				if(assembleList.getComponents().get(i).getComponentID() == ab.getComponentID()){
					assembleList.getComponents().get(i).setComponentNO(assembleList.getComponents().get(i).getComponentNO() + ab.getComponentNO());
					addFlag = false;
				}
			}
			if(addFlag){
				assembleList.getComponents().add(ab);
			}
			
			sess.setAttribute(ASSEMBLE_LIST, assembleList);		
			request.getRequestDispatcher(pageNewProduct).forward(request,response);
		}
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		processRequest(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		processRequest(request, response);
	}

	private void gotoErrorPage(HttpServletRequest request,
			HttpServletResponse response, String errorMessage)
			throws ServletException, IOException {
		ErrorBean error = new ErrorBean();
		error.setMessage(errorMessage);
		request.setAttribute(ERROR, error);
		request.getRequestDispatcher(pageError).forward(request, response);
	}

}
